package com.gobo.orderservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gobo.commonutils.JwtUtils;
import com.gobo.commonutils.R;
import com.gobo.orderservice.pojo.Order;
import com.gobo.orderservice.service.OrderService;
import com.gobo.servicebase.handler.exception.pojo.GoboException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author gobo-generator
 * @since 2021-09-25
 */
@RestController
@RequestMapping("/orderservice/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    //根据课程ID以及用户ID创建订单
    @PostMapping("/create/{courseId}")
    public R createOrder(@PathVariable String courseId, HttpServletRequest request){
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        if (StringUtils.isEmpty(memberId)){
            throw new GoboException(30001,"用户信息不存在，请重新登录！");
        }
        String orderId = orderService.saveOrder(courseId, memberId);
        return orderId!=null?R.ok().data("orderNo",orderId):R.error().message("生成订单失效");
    }

    @GetMapping("getOrder/{orderId}")
    public R get(@PathVariable String orderId) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",orderId);
        Order order = orderService.getOne(wrapper);
        return R.ok().data("item", order);
    }

    @PostMapping("getOrderStatus/{courseId}/{memberId}")
    public boolean getOrderStatusByCourseIdAndMemberId(@PathVariable String courseId,@PathVariable String memberId){

        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("member_id",memberId);
        queryWrapper.eq("course_id",courseId);
        queryWrapper.eq("status",1);
        int count = orderService.count(queryWrapper);
        return count>0;
    }

}

